/*
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Edited by: Dennis Feng
 * Created: 12 April 2012
 * 
 * Summary: Edits a single task. Geolocation is used on the address to get a
 * corresponding latitude and longitude. There is one activity that can be launched
 * from this one.  You can launch to the map activity to search for an address.
 */

package sfsu.memopad;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class NoteEdit extends Activity {
	// Activity Id Numbers.
	private static final int MAP = 0;
	
	// Layout objects.
	private EditText mTitleText;
	private EditText mBodyText;
	private EditText mAddressText;
	private EditText mLatitudeText;
	private EditText mLongitudeText;
	private Button confirmButton;
	private ImageButton mapBrowseButton;
	private CheckBox doneCheckBox;

	// Activity variables
	private TaskData task = new TaskData();
	private String ownerName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.note_edit);
		setTitle(R.string.individual_task);

		//mTaskIDText = (TextView) findViewById(R.id.taskID);
		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);
		mAddressText = (EditText) findViewById(R.id.address);
		mLatitudeText = (EditText) findViewById(R.id.latitude);
		mLongitudeText = (EditText) findViewById(R.id.longitude);
		
		confirmButton = (Button) findViewById(R.id.confirm);
		mapBrowseButton = (ImageButton) findViewById(R.id.mapButton);
		
		doneCheckBox = (CheckBox) findViewById(R.id.doneCheckBox);

		Bundle extras = getIntent().getExtras();
		String passData = "";

		// Pulls task data passed from main activity.
		if (extras != null) {
			passData = extras.getString("PASSDATA");
			if (!passData.contentEquals("")) {
				task.parseString(passData);
				populateFields();
			}
			ownerName = extras.getString("USERNAME");
		}
		
		// Sets checkbox is the task is flagged as completed.
		if(task.isTaskCompleted()) {
			doneCheckBox.setChecked(true);
		}

		// Switch to map activity.
		mapBrowseButton.setOnClickListener(new OnClickListener(){
			public void onClick (View v){
				try {
					goMapBrowse();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
				
		confirmButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (fieldsFilled()) {
					//setResult(RESULT_OK);
					storeMemoData();
					finish();
				}
			}
		});
		
		doneCheckBox.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				if(doneCheckBox.isChecked()) {
					task.setIsTaskCompleted(true);
					task.setIsNotificationOn(false);
				} else {
					task.setIsTaskCompleted(false);
					task.setIsNotificationOn(true);
				}
			}
		});
	}
	
	// Handles actions after returning from a particular activity.
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (requestCode) {
		case MAP:
			task.setLatitude(intent.getExtras().getDouble("LATITUDE"));
			task.setLongitude(intent.getExtras().getDouble("LONGITUDE"));
			task.setAddress(intent.getExtras().getString("ADDRESS"));
			populateFields();
			break;
		}
	}
	
	// Go to Map browser.
	private void goMapBrowse(){
		Intent launchMap = new Intent (this, MapActivity.class);
		startActivityForResult(launchMap, MAP);
	}

	// Checks that Title, Body, Address fields are filled.
	private boolean fieldsFilled() {
		if ((mTitleText.getText().toString().contentEquals(""))
				|| (mBodyText.getText().toString().contentEquals(""))
				|| (mAddressText.getText().toString().contentEquals(""))) {
			Toast.makeText(this, "Blank Fields.", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}

	// Updates fields with task data.
	private void populateFields() {
		//mTaskIDText.setText(task.getTaskId());
		mTitleText.setText(task.getTitle());
		mBodyText.setText(task.getTaskBody());
		mAddressText.setText(task.getAddress());
		mLatitudeText.setText(Double.toString(task.getLatitude()));
		mLongitudeText.setText(Double.toString(task.getLongitude()));
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveState();
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}
	
	@Override
	public void onBackPressed() {
		storeMemoData();
		finish();
	}

	// Pulls all infomation from the text boxes and updates the task.
	private void saveState() {
		task.setTitle(mTitleText.getText().toString());
		task.setTaskBody(mBodyText.getText().toString());
		task.setAddress(mAddressText.getText().toString());
		task.setOwner(ownerName);
		
		/*
		 *  Used only for debugging while using the emulator for testing because
		 *  location features not available for the emulator. Use the commented
		 *  getGeoLocation() for actual testing on an Android phone.
		 */
		if (mLatitudeText.getText().toString() != "") {
			task.setLatitude(Double.valueOf(mLatitudeText.getText().toString()));
		}
		if (mLongitudeText.getText().toString() != "") {
			task.setLongitude(Double.valueOf(mLongitudeText.getText().toString()));
		}
		
		/*
		//Use the given address and pulls the geolocation using the geolocation function.
		getGeoLocation(task.getAddress()); 
		*/
	}

	// Readies the task to be sent back to the main activity as an extra.
	protected void storeMemoData() {
		saveState();
		Intent intent = new Intent();
		intent.putExtra("PASSDATA", task.toString());
		setResult(RESULT_OK, intent);
	}
	
	/*
	 * Geolocation using location to get latitude and longitude from an address.
	 */
	private void getGeoLocation(String myAddress) {
		List<Address> addresses;
		Geocoder geoCoder = new Geocoder(this);
		try {
			addresses = geoCoder.getFromLocationName(myAddress, 1);
			if(addresses != null) {
				Address x = addresses.get(0);
				task.setLatitude(x.getLatitude());
				task.setLongitude(x.getLongitude());
			}
		} catch(IOException e) {
			Log.d("NoteEdit", "Error getting geolocation: " + e.getMessage());
		}
	}
}
